package com.termux.project;
import java.io.*;
import com.termux.view.*;
import com.termux.mvp.BasePresenter;
import com.termux.ide.MainActivity;
import com.jsdroid.fileview.*;
import com.termux.app.*;
import com.alibaba.fastjson.*;
import com.termux.commons.*;
import android.content.*;
import com.termux.util.*;
import java.util.*;
import android.preference.*;
import android.util.*;
import com.termux.util.Logger;
import com.qmuiteam.qmui.widget.dialog.*;
public class CodePresenter extends BasePresenter<MainActivity>
{
	private Project project;

	String cwd = "";
	static final String PROJECT_KEY = "lastOrStoreProject_KEY";
	public void updateProject(String name,String cflag,String libs,String type)
	{
		// TODO: Implement this method
		project.name = name;
		project.CFLAGS.setLength(0);
		project.CFLAGS.append(cflag);
		project.libs.setLength(0);
		project.libs.append(libs);
		project.type = type;
	}

	public void openLog()
	{
		// TODO: Implement this method
	}
	public void openTermux()
	{
		//getView().startActivity(new Intent(getView(), TermuxActivity.class));
	}
	public void toShowErr(String msg, final int ms)
	{
	final QMUITipDialog dialog = TipHelper.showError(getView(), msg);
			new Thread(){
				@Override
				public void run(){
					try
					{
						Thread.sleep(ms);
						dialog.dismiss();
					}
					catch (InterruptedException e)
					{}
				}
			}.start();
	}
	public void compileProject()
	{
		// TODO: Implement this method
		if (project == null)
		{
			toShowErr("无项目。。。", 1000);
			return;
		}
		if (!project.generateCMakeFile())
		{
			toShowErr("CMakeLists.txt生成失败！", 1000);
			return ;
		}
		CompileTask cmakeCompileTask =new  CompileTask(project.projectRootDir + "/build", TermuxService.PREFIX_PATH + "/bin/cmake", new String[]{".."});
		cmakeCompileTask.attachView(getView());
		if (cmakeCompileTask.exec() != 0)
		{
			toShowErr("cmake编译失败。。。", 1000);
			return;
		}
		CompileTask makeTask = new CompileTask(project.projectRootDir + "/build", TermuxService.PREFIX_PATH + "/bin/make", new String[]{"-j",String.valueOf(Runtime.getRuntime().availableProcessors() - 2)});
		makeTask.attachView(getView());
		if (makeTask.exec() != 0)
		{
			toShowErr("make编译失败。。。", 1000);
			return;
		}
		else {
			toShowErr("编译成功", 1000);
		}
	}

	public void runProject()
	{
		// TODO: Implement this method
		if (project == null)
		{
			toShowErr("无项目。。。", 1000);
			return;
		}
		File output = null;
		
		if (!project.type.equals("Console"))
		{
			output = new File(project.projectRootDir + "/build/lib/lib" + project.name+".so");
		}
		else
			output = new File(project.projectRootDir + "/build/" + project.name);
		
		if (!output.exists())
		{

			toShowErr("请先成功编译项目！", 1000);
			return;
		}
		FileUtil.copyFile(output, new File(Project.OUTFILE));
		new File(Project.OUTFILE).setExecutable(true);
		// TODO: 运行程序。。。
		if (project.type.equals("Console"))
		{
			getView().addExecSession(Project.OUTFILE,null,project.projectRootDir,project.name);
		}
		else if(project.type.equals("NativeActivity"))
		{
			
		}
		else if (project.type.equals("OpenGLES"))
		{
			Intent intent = new Intent(getView(),GlesActivity.class);
			intent.putExtra("fname",Project.OUTFILE);
			getView().startActivity(intent);
		}
		else if (project.type.equals("SDL2"))
		{
			Intent intent = new Intent(getView(),Sdl2Activity.class);
			intent.putExtra("fname",Project.OUTFILE);
			
			getView().startActivity(intent);
		}
	}
	
	public void openProject(File configFile)
	{
		if (!configFile.exists()) {
			return;
		}
		JSONObject config = JSON.parseObject(FileUtil.read(configFile));
		project = new Project(config.getString("name"), config.getString("pkg"), configFile.getParent());
		project.CFLAGS.append(config.getString("cflag"));
		project.libs.append(config.getString("libs"));
		project.type = config.getString("type");
		PreferenceManager.getDefaultSharedPreferences(getView()).edit().putString(PROJECT_KEY, configFile.getAbsolutePath()).apply();
		initProjectUI();
	}
	
	public void openProject()
	{
		// TODO: Implement this method

        if (project == null)
		{
			if (PreferenceManager.getDefaultSharedPreferences(getView()).getString(PROJECT_KEY,null) == null)
			{
				getView().getFileView().setRootFile(new File("/sdcard"),null);
				return;
			}
			openProject(new File(PreferenceManager.getDefaultSharedPreferences(getView()).getString(PROJECT_KEY,null)));
        }
	}
	private void initProjectUI(){
		getView().setTitle(project.name);
        getView().setProjectDir(new File(project.projectRootDir));

        initFileDesc(new File(project.projectRootDir));

        File scriptFile = new File(project.projectRootDir, "Srcs/main.cpp");
        if (scriptFile.exists())
		{
            try
			{
                getView().openFile(scriptFile);
            }
			catch (Exception e)
			{
                e.printStackTrace();
            }
        }
		else
		{
            getView().showFileTree();
        }
	}
	private void initFileDesc(File projectDir)
	{
		// TODO: Implement this method
		FileView fileView = getView().getFileView();
        fileView.putDesc(new File(projectDir, "Srcs"), "源文件");
        fileView.putDesc(new File(projectDir, "Headers"), "头文件");
        fileView.putDesc(new File(projectDir, "Assets"), "资源文件");
		fileView.putDesc(new File(projectDir, "build"), "编译文件");
        fileView.putDesc(new File(projectDir, "config.json"), "项目属性");

	}
}
